package net.azure.app.view;

import net.azure.app.Azure;
import net.azure.app.util.Reflector;
import net.azure.app.model.AzureSession;
import net.azure.app.model.Story;

import javax.swing.*;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import java.awt.*;

/**
 * Created by IntelliJ IDEA.
 * User: Venkatraman Kandaswamy : kvenkatraman@gmail.com
 * Date: 15-Jul-2008
 * Time: 06:26:02
 */
public class StoryView implements AzureView {

    public void renderView(Component component, Azure azure) {
        Story currentStory = AzureSession.getCurrentStory();

        Reflector.copyValuesFromTo(currentStory.getStoryDetails(),azure,"Text", "Text");
        Reflector.copyValuesFromTo(currentStory.getRisk(),azure,"Combo","SelectedItem");
        Reflector.copyValuesFromTo(currentStory.getEstimate(),azure,"Combo","SelectedItem");
        ListModel lm = new StaticListModel();
        azure.getMslList().setModel(lm);

        azure.getMslList().addListSelectionListener(new MslListSelectionListener());
    }

    class StaticListModel implements ListModel {
        private final Object[] data = AzureSession.getMsls();

        public Object getElementAt(int index) {
            return data[index];
        }

        public int getSize() {
            return data.length;
        }

        public void addListDataListener(ListDataListener ldl) {
            // since the list never changes, we don't need this :-)
        }

        public void removeListDataListener(ListDataListener ldl) {
            // since the list never changes, we don't need this :-)
        }
    }

    private class MslListSelectionListener implements ListSelectionListener {
        public void valueChanged(ListSelectionEvent e) {
            boolean adjust = e.getValueIsAdjusting();
            if (!adjust) {
                JList list = (JList) e.getSource();
                Object selectionValues[] = list.getSelectedValues();
                if (selectionValues.length > 0) {
                    Story story = AzureSession.getStories().get(selectionValues[0]);
                    AzureSession.setMSL(story.getMSL());
                    AzureSession.getAzure().createUIComponents();
                }
            }
        }
    }
}
